#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on Mar 21, 2014, by Junn
# 
#

from django.contrib.auth.models import BaseUserManager
from django.utils import timezone
from utils import eggs, logs
from django.core.cache import cache

VALID_ATTRS = ('nickname', 'email', 'phone', 'gender', 'avatar', 'city')

def mk_key(id):
    return 'u%s' % id

class CustomUserManager(BaseUserManager):
    def _create_user(self, username, password=None, is_active=True, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not username:
            raise ValueError('The given username must be set')
        user = self.model(username=username,
                          is_staff=False, is_active=is_active, is_superuser=False,
                          last_login=now, date_joined=now, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def get_by_phone(self, phone):
        try:
            return self.get(username=phone)
        except self.model.DoesNotExist:
            return None         

    def update_user(self, user, req):
        data = req.DATA
        for attr in VALID_ATTRS:  #双重循环, 以后需要改进算法
            if attr in data:
                setattr(user, attr, data.get(attr))

        user.save(using=self._db)
        return user


    def create_superuser(self, username, password, **extra_fields):
        u = self._create_user(username, password, **extra_fields)
        u.is_staff = True
        u.is_superuser = True
        u.save(using=self._db)
        return u
    
    def create_implicit_user(self): #unused
        '''第3方隐式登录时,需要自动创建一个用户账号'''
        username = 'g_%' % eggs.gen_uuid1()
        password = '123456'
        return self._create_user(username, password)

    ############################################################   cache methods
    def cache_all(self):    #TODO: abstract these cache_xxx method into base class ...
        users = self.all()
        for u in users:
            u.cache()
            
        logs.info('====================================> All user entities cached.')   
    
    def get_cached(self, uid): #TODO: using cache later...
        user = cache.get(mk_key(uid))
        if not user:
            try:
                user = self.get(id=int(uid))
                user.cache()
            except self.model.DoesNotExist:
                logs.err(__name__, eggs.lineno(), 'User not found: %s' % uid)
                return None
            except Exception, e:
                logs.err(__name__, eggs.lineno(), 'get_cached user error: %s' % e)
                return None
            
        return user    
        
    
    
    